package newsy;

import com.google.wave.api.Range;
import com.google.wave.api.TextView;

public final class TextProcessor {
  // char constants
  private final static char QUERY_OPEN = '[';
  private final static char QUERY_CLOSE = ']';

  // wave syntax constants
  private final static String ANNOTATION_LINK = "link/manual";

  // functional parameters
  private final static String SEARCH_PROVIDER = "http://news.google.com/news/search?q=";

  /**
   * Function that changes the code between <c> and </c>
   * 
   * @param tv
   *          The TextView to be changed
   */
  public final static void process(TextView tv) {
    String text = tv.getText();
    int start = 0, end = 0;
    final int length = text.length();
    while (start < length) {
      if (text.charAt(start) == QUERY_OPEN) {
        end = start + 1;
        while (text.charAt(end) != QUERY_CLOSE) {
          end++;
          if (end > length) {
            break;
          }
        }
        if (end <= length) {
          Range r = new Range(start + 1, end);
          tv.setAnnotation(r, ANNOTATION_LINK, SEARCH_PROVIDER + tv.getText(r));
        }
      }
      start++;
    }
  }
}
